package com.tdtxdcxm.ruralcommunity.slice;


import com.tdtxdcxm.ruralcommunity.ResourceTable;
import com.tdtxdcxm.ruralcommunity.appruntime.DataCenterControl;
import com.tdtxdcxm.ruralcommunity.appruntime.UserConfigInfo;
import com.tdtxdcxm.ruralcommunity.httpmanagers.ThreadPoolUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class LoginSlice extends AbilitySlice implements Component.ClickedListener{
    private String[][] userinfodown = new String[5][2];
    private Boolean toanotherslice = false;

    private TextField log_usernametfd,log_passwordtfd;
    private Button submitlogin,log_lbackbt;
    private Text log_tstext;

    private String[] userInfo = new String[2];
    /*<****************http构造表单上传注登录数据区域*****************/
    public void UpDataLoginInfo(String[] userinfo){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;

            String urlString = DataCenterControl.serverIpWithPort + "login/?";
            try {
                URL url = new URL(urlString);

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;

                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();

                    stringBuilder.append("username");
                    stringBuilder.append("=");
                    stringBuilder.append(userinfo[0]);
                    stringBuilder.append("&");
                    stringBuilder.append("password");
                    stringBuilder.append("=");
                    stringBuilder.append(userinfo[1]);


                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();

                    try {
                        InputStream inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = new String(outputStream.toByteArray());


                    String[] userinfos = result.split(",");

                    if(userinfos[0].equals("OK")){
                        userinfodown[0][0] = "username";
                        userinfodown[0][1] = userinfos[1];

                        userinfodown[1][0] = "password";
                        userinfodown[1][1] = userinfos[2];

                        userinfodown[2][0] = "email";
                        userinfodown[2][1] = userinfos[3];

                        userinfodown[3][0] = "gender";
                        userinfodown[3][1] = userinfos[4];

                        userinfodown[4][0] = "age";
                        userinfodown[4][1] = userinfos[5];

                        UserConfigInfo.pushData(this.getContext(),userinfodown);
                        DataCenterControl.userName = userinfo[0];
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                log_tstext.setText("登录成功");
                                log_usernametfd.setText("");
                                log_passwordtfd.setText("");

                                DataCenterControl.age = userinfos[5];
                                DataCenterControl.gender = userinfos[4];

                                toanotherslice = true;
                            }
                        });
                        present(new MainAbilitySlice(),new Intent());
                    }
                    else{
                        if(userinfos[0].equals("NOT")){
                            getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    log_tstext.setText("远程验证：账号未注册！");
                                }
                            });
                        }
                        if(userinfos[0].equals("NO")){
                            getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    log_tstext.setText("远程验证：密码错误！");
                                }
                            });
                        }
                    }
                }
            } catch (IOException e) {

            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http构造表单上传登录数据区域***************>*/

    private void initLogComponent(){
        log_usernametfd = (TextField) findComponentById(ResourceTable.Id_log_usernametfd);
        log_passwordtfd = (TextField) findComponentById(ResourceTable.Id_log_passwordtfd);
        submitlogin = (Button) findComponentById(ResourceTable.Id_submitlogin);
        log_lbackbt = (Button) findComponentById(ResourceTable.Id_log_lbackbt);
        log_tstext = (Text) findComponentById(ResourceTable.Id_log_tstext);

        submitlogin.setClickedListener(this);
        log_lbackbt.setClickedListener(this);

        log_passwordtfd.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if(!s.equals("") && !s.matches("^[0-9]+$")){
                    log_tstext.setText("只能是数字");
                    log_passwordtfd.setText(s.substring(0,s.length() - 1));
                }
            }
        });
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_loginpage);

        initLogComponent();
    }

    @Override
    public void onActive() {
        super.onActive();
        log_tstext.setText("您好！");
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if(toanotherslice){
            terminate();
        }

    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    public void onClick(Component component) {
        if(component == submitlogin){
            if(log_usernametfd.getText().equals("")){
                log_tstext.setText("账号不能为空！");
                return;
            }
            if(log_passwordtfd.getText().equals("")){
                log_tstext.setText("密码不能为空！");
                return;
            }
            if(log_passwordtfd.getText().length() > 8){
                log_tstext.setText("密码不能超过8位！");
                return;
            }
            log_tstext.setText("正在登录中......");

            String inputname = log_usernametfd.getText();
            String inputpassword = log_passwordtfd.getText();
            userInfo[0] = inputname;
            userInfo[1] = inputpassword;

            if(UserConfigInfo.compareData(this,inputname,"username",inputname) == true){
                if(UserConfigInfo.compareData(this,inputname,"password",inputpassword) == true){
                    log_usernametfd.setText("");
                    log_passwordtfd.setText("");
                    log_tstext.setText("本地验证：密码正确！");

                    DataCenterControl.userName = userInfo[0];
                    UserConfigInfo.pullData(this.getContext(),userInfo);

                    present(new MainAbilitySlice(),new Intent());

                    toanotherslice = true;
                }
                else{
                    log_tstext.setText("本地验证：密码错误！");
                    return;
                }
            }
            else{
                log_tstext.setText("本地验证：未从该机注册！远程验证...");
                UpDataLoginInfo(userInfo);
            }
        }
        if(component == log_lbackbt)
        {
            log_usernametfd.setText("");
            log_passwordtfd.setText("");
            present(new StartPage(),new Intent());
            toanotherslice = true;
        }
    }
}
